/*
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 *
 * Copyright @2008 the original author or authors.
 */
package com.bluestone.report;

import java.io.File;
import java.util.Map;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;

import com.bluestone.util.Util;

/**
 * A report tool. 
 * @author <a href="mailto:ming7655@gmail.com">Aaron</a>
 */
public class ExportTool {
	public static String TYPE_HTML = "HTML";

	public static String TYPE_PDF = "HTML";

	private static ExportTool INSTANCE = null;

	public static ExportTool getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new ExportTool();
		}
		return INSTANCE;
	}

	private ExportTool() {

	}

	/**
	 * 
	 * @param type String that defines the report type.
	 * @param templateFilePath String that define the JasperReport report template file path.
	 * @param destFilePath String that defines the output report file path.
	 * @param dataSource ProjectReportDataSource that defines the JavaBean DateSource for the JasperReport.
	 * @param params Map that defines the parameters for the report template.
	 */
	public void exportToFile(String type, String templateFilePath,
			String destFilePath, ProjectReportDataSource dataSource, Map params) {
		try {
			File reportFile = new File(templateFilePath);
			if (!reportFile.exists()) {
				Util.warn("The template file of "+ templateFilePath+" is not exsit.");
				return;
			}

			JasperReport jasperReport = JasperCompileManager
					.compileReport(reportFile.getPath());
			JasperPrint jasperPrint = JasperFillManager.fillReport(
					jasperReport, params, dataSource);
			File destFile = new File(destFilePath);
			if (!destFile.exists()) {
				destFile.createNewFile();
			}
			if (TYPE_HTML.equals(type)) {
				JasperExportManager.exportReportToHtmlFile(jasperPrint,
						destFilePath);
			}else if(TYPE_PDF.equals(type)){
				JasperExportManager.exportReportToPdfFile(jasperPrint,
						destFilePath);
			}
		} catch (Exception e) {
			Util.error(e);
		}
	}
}
